package com.ls.lserp.modules.purchase.web;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.purchase.entity.PuttingRequest;
import com.ls.lserp.modules.purchase.service.PuttingRequestService;
import com.ls.lserp.modules.sys.entity.User;
import com.ls.lserp.modules.sys.utils.SequenceUtil;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

@Controller
@RequestMapping(value = "${adminPath}/putting/request/")
public class PuttingRequestController extends BaseController {

	// 保存 编辑 删除 方法
	@Autowired
	private PuttingRequestService puttingRequestService;
	@Autowired
	Configuration freemarkerConfiguration;

	@ModelAttribute
	public PuttingRequest get(@RequestParam(required = false) String id) {

		// 判断id是否为空
		if (StringUtils.isNotBlank(id)) {
			// 执行查询语句 查询基本信息
			return puttingRequestService.get(Long.parseLong(id));
		} else {
			// 若为空，实例化
			return new PuttingRequest();
		}
	}

	/**
	 * @Title: 画面跳转用
	 * @return url
	 */
	@RequiresPermissions("putting:request:view")
	@RequestMapping(value = { "" })
	public String list(Model model) {
		// 画面跳转
		return "modules/purchase/puttingRequest";
	}

	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param puttingRequest
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws Exception
	 */
	@RequiresPermissions("putting:request:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(PuttingRequest puttingRequest, HttpServletRequest request, HttpServletResponse response,
			Model model) throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "puttingRequest");
		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		// 出库申请单号
		searchParam.append("&inventoryRequestNo=");
		searchParam.append(puttingRequest.getInventoryRequestNo());
		// 生产制单号
		searchParam.append("&contractProcessNo=");
		searchParam.append(puttingRequest.getContractProcessNo());
		// 客户订单号
		searchParam.append("&indentNo=");
		searchParam.append(puttingRequest.getIndentNo());
		// 日期
		searchParam.append("&dateFrom=");
		searchParam.append(puttingRequest.getDateFrom());
		searchParam.append("&dateTo=");
		searchParam.append(puttingRequest.getDateTo());
		// 状态
		searchParam.append("&tabPageStatus=");
		searchParam.append(puttingRequest.getTabPageStatus());
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());
		
		// 查询一览页面数据
		Page<PuttingRequest> page = puttingRequestService.findList(new Page<PuttingRequest>(request, response),puttingRequest);
		// 读取系统路径
		String strUri = request.getContextPath() + Global.getAdminPath();
		// 读取文件生成字符串
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		map.put("adminUri", strUri);
		map.put("puttingRequests", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
		strHtml = FreeMarkerTemplateUtils
				.processTemplateIntoString(freemarkerConfiguration.getTemplate("puttingRequest.ftl"), map);
		listMap.put("puttingRequest", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}
	
	/**
	 * 进入编辑页面
	 * @param puttingRequest
	 * @param model
	 * @return
	 */
	@RequiresPermissions("putting:request:edit")
	@RequestMapping(value = "form")
	public String form(PuttingRequest puttingRequest,Model model,HttpSession session) {
		// 获取当前用户
				User curLoginUser = puttingRequest.getCurrentUser();
		
		List<PuttingRequest> findFabricatingList = puttingRequestService.findFabricatingList();
		puttingRequest.setFabricatingList(findFabricatingList);
		if(puttingRequest.getId() == null){
			// 出库单条码
			puttingRequest.setStockBarCode(SequenceUtil.inventoryRequestbarcode().getReturnCode());
			// 申请人
			puttingRequest.setRequestUser(curLoginUser.getFirstName() + curLoginUser.getLastName());
			puttingRequest.setRequestUserId(curLoginUser.getId());
			// 申请日期
			puttingRequest.setRequestDate(new Date());
			
			// 下拉菜单（客供入库）
			puttingRequest.setInventoryCategory(ResourcesUtil.getConfig("outbound_category_putting"));
		}else{
		   	   // 查找出库申请明细
			   List<PuttingRequest> resultRequestList = puttingRequestService.findRequestDetail(puttingRequest);
			   puttingRequest.setRequestDetailsList(resultRequestList);
			   
		}
		
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("puttingRequest", puttingRequest);
		
		// 返回页面地址
		return "modules/purchase/puttingRequestCreate";
	}
	
	/**
	 * 生产制单联动
	 * @param model
	 * @return
	 */
	@RequiresPermissions("putting:request:view")
	@RequestMapping(value = "contractProcessFun")
	public String contractProcessFun(PuttingRequest puttingRequest, Model model,HttpSession session) {
		
		List<PuttingRequest> styleList = puttingRequestService.findStyleList(puttingRequest);
		puttingRequest.setStyleList(styleList);
		
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("puttingRequest", puttingRequest);
		
		// 返回页面地址
		return "modules/purchase/puttingRequestCreate";
	}
	/**
	 * 款式联动
	 * @param model
	 * @return
	 */
	@RequiresPermissions("putting:request:view")
	@RequestMapping(value = "styleFun")
	public String styleFun(PuttingRequest puttingRequest, Model model,HttpSession session) {
		
		puttingRequest = puttingRequestService.getPuttingContractInfo(puttingRequest);
		
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("puttingRequest", puttingRequest);
		
		// 返回页面地址
		return "modules/purchase/puttingRequestCreate";
	}
	/**
	 *加工厂联动
	 * @param model
	 * @return
	 */
	@RequiresPermissions("putting:request:view")
	@RequestMapping(value = "fabricatingFun")
	public String fabricatingFun(PuttingRequest puttingRequest, Model model,HttpSession session) {
		
		List<PuttingRequest> contractProcessList = puttingRequestService.findPuttingContractList(puttingRequest);
		puttingRequest.setContractProcessList(contractProcessList);
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("puttingRequest", puttingRequest);
		
		// 返回页面地址
		return "modules/purchase/puttingRequestCreate";
	}
	
    
    
   
   /**
    * 保存信息
    * @param puttingRequest
    * @param request
    * @param model
    * @param response
    * @return
    * @throws ResourceException 
    */
   @RequiresPermissions("putting:request:edit")
   @RequestMapping(value = "save")
   @ResponseBody
   public String save(PuttingRequest puttingRequest, HttpServletRequest request, Model model, HttpServletResponse response , HttpSession session) throws ResourceException {

		// 判断id是否为null （判断新建或修改）
		if(puttingRequest.getId()!=null){
			// 编辑数据
			// 判断数据是否删除
			PuttingRequest puttingRequestNew = get(puttingRequest.getId().toString());
			// 判断数据是否删除
           if(puttingRequestNew==null || BaseEntity.DEL_FLAG_DELETE.equals(puttingRequestNew.getDeleteFlag())){
           	// 返回提示信息
           	return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
           }
			
           // 排他处理
		    if(puttingRequest.getVersion()==get(puttingRequest.getId().toString()).getVersion()){
		    	
		    	// 版本号加1
		    	puttingRequest.setVersion(puttingRequest.getVersion()+1);
		    }else{
		    	
		    	// 返回提示信息
		        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
		    }
		}
	   
   	   // 保存入库申请
		puttingRequestService.savePuttingRequest(puttingRequest);
   	
   	   // 保存成功返回提示信息
       return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "inventory_request_save_success")));
   }
   
	/**
    * 进入查看页面
    * @param model
    * @return
    */
   @RequiresPermissions("putting:request:view")
   @RequestMapping(value = "show")
   public String show(PuttingRequest puttingRequest, Model model) {
	   
   	   // 查找出库申请明细
	   List<PuttingRequest> resultRequestList = puttingRequestService.findRequestDetail(puttingRequest);
	   puttingRequest.setRequestDetailsList(resultRequestList);
   	
       // 将查询结果赋值mvc model层返回jsp页面
       model.addAttribute("puttingRequest", puttingRequest);
       
       // 返回页面地址
       return "modules/purchase/puttingRequestShow";
   }
    
   
}
